package cc.customer.system.service.impl;

import cc.customer.common.domain.ResponseBo;
import cc.customer.common.service.impl.BaseService;
import cc.customer.common.utils.Utils;
import cc.customer.system.dao.UserMapper;
import cc.customer.system.dao.UserRoleMapper;
import cc.customer.system.domain.MyUser;
import cc.customer.system.domain.UserRole;
import cc.customer.system.domain.UserWithRole;
import cc.customer.system.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static cc.customer.common.utils.FebsUtil.isPhoneNo;

@Service("userService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl extends BaseService<MyUser> implements UserService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public MyUser findByNameOrMobile(String var) {
        Example example = new Example(MyUser.class);
        boolean isMobile = isPhoneNo(var);
        if (isMobile) {
            example.createCriteria().andCondition("mobile=", var);
        } else {
            example.createCriteria().andCondition("lower(username)=", var.toLowerCase());
        }
        List<MyUser> list = this.selectByExample(example);
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public MyUser findByName(String userName) {
        Example example = new Example(MyUser.class);
        example.createCriteria().andCondition("lower(username)=", userName.toLowerCase());
        List<MyUser> list = this.selectByExample(example);
        return list.isEmpty() ? null : list.get(0);
    }


    @Override
    public List<MyUser> findUserWithDept(MyUser user) {
        try {
            return this.userMapper.findUserWithDept(user);
        } catch (Exception e) {
            log.error("error", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<MyUser> findUserWithDeptAllUser(MyUser user) {
        try {
            return this.userMapper.findUserWithDeptAllUser(user);
        } catch (Exception e) {
            log.error("error", e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional
    public void addUser(MyUser user, Long[] roles) {
        user.setCrateTime(new Date());
        user.setTheme(MyUser.DEFAULT_THEME);
        user.setAvatar(MyUser.DEFAULT_AVATAR);
        user.setUserUuid(Utils.getUUID());
        this.save(user);
        setUserRoles(user, roles);
    }

    private void setUserRoles(MyUser user, Long[] roles) {
        Arrays.stream(roles).forEach(roleId -> {
            UserRole ur = new UserRole();
            ur.setUserId(user.getUserId());
            ur.setRoleId(roleId);
            this.userRoleMapper.insert(ur);
        });
    }

    @Override
    @Transactional
    public void updateUser(MyUser user, Long[] roles) {
        user.setPassword(null);
        user.setUsername(null);
        user.setModifyTime(new Date());
        this.updateNotNull(user);
        Example example = new Example(UserRole.class);
        example.createCriteria().andCondition("user_id=", user.getUserId());
        this.userRoleMapper.deleteByExample(example);
        setUserRoles(user, roles);
    }

    /**逻辑删除用户**/
    @Override
    @Transactional
    public void batchUpdateUser(String userIds){
        List<String> list = Arrays.asList(userIds.split(","));
        MyUser myUser = new MyUser();
        myUser.setStatus("0");
        this.batchUpdate(list, "userId", MyUser.class,myUser);
        //删除用户的角色
        //this.userRoleService.deleteUserRolesByUserId(userIds);
    }

    @Override
    @Transactional
    public void updatePassword(String password, String username) {
        Example example = new Example(MyUser.class);
        example.createCriteria().andCondition("username=", username);
        MyUser user = new MyUser();
        user.setPassword(password);
        this.userMapper.updateByExampleSelective(user, example);
    }

    @Override
    public UserWithRole findById(Long userId) {
        List<UserWithRole> list = this.userMapper.findUserWithRole(userId);
        List<Long> roleList = new ArrayList<>();
        for (UserWithRole uwr : list) {
            roleList.add(uwr.getRoleId());
        }
        if (list.isEmpty()) {
            return null;
        }
        UserWithRole userWithRole = list.get(0);
        userWithRole.setRoleIds(roleList);
        return userWithRole;
    }

    @Override
    public MyUser findUserProfile(MyUser user) {
        return this.userMapper.findUserProfile(user);
    }

    @Override
    @Transactional
    public void updateUserProfile(MyUser user) {
        user.setUsername(null);
        user.setPassword(null);
        this.updateNotNull(user);
    }

    /**根据姓名查用户*/
    @Override
    public List<MyUser> selectUserByName(MyUser user){
        List<MyUser> list = new ArrayList<>();
        try {
            Example example = new Example(MyUser.class);
            Example.Criteria criteria=  example.createCriteria();
            if (!StringUtils.isEmpty(user.getUsername())){
                criteria.andLike("nickname","%"+user.getUsername()+"%");
            }
            list = this.selectByExample(example);
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    /**根据邀请码查员工id*/
    @Override
    public List<MyUser> findByCode(){
        try{
            Example example = new Example(MyUser.class);
            Example.Criteria criteria=  example.createCriteria();
            criteria.andIsNotNull("byCode");
            return this.selectByExample(example);
        }catch (Exception e){
            log.error("根据邀请码查询所有的用户失败:"+e.getMessage());
        }
       return new ArrayList<>();
    }

    /**根据部门查员工*/
    @Override
    public List<MyUser> selectUserByDeptid(MyUser user){
       try{
           List<String> list = Arrays.asList(user.getDeptId().toString().split(","));
               Example example = new Example(MyUser.class);
               example.createCriteria().andIn("deptId",list).andEqualTo("status","1");
               return this.selectByExample(example);
       }catch (Exception e){
           e.printStackTrace();
           return new ArrayList<>();
       }
    }

    @Override
    public List<MyUser> selectUserByDeptid2User(String deptids) {
        try{
            List<String> list = Arrays.asList(deptids.split(","));
            Example example = new Example(MyUser.class);
            example.createCriteria().andIn("deptId",list).andEqualTo("status","1");
            return this.selectByExample(example);
        }catch (Exception e){
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    /**根据uui的查询用户详情**/
    @Override
    public MyUser findUserByUuids(String userUuid) {
        try {
            Example example = new Example(MyUser.class);
            Example.Criteria criteria=  example.createCriteria();
            criteria.andEqualTo("userUuid",userUuid);
            List<MyUser> myUser = this.selectByExample(example);
            if (!myUser.isEmpty()){
                return myUser.get(0);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public MyUser selectUserByDingDing(String dingding) {
        try {
            Example example = new Example(MyUser.class);
            Example.Criteria criteria=  example.createCriteria();
            criteria.andEqualTo("dingUserid",dingding);
            List<MyUser> myUser = this.selectByExample(example);
            if (!myUser.isEmpty()){
                return myUser.get(0);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public MyUser findUserDetailByUuids(String userUuid) {
        try {
            MyUser user = userMapper.selectUserDetailByUuid(userUuid);
            return user==null ? null : user;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * app更新我的基本信息
     * @param user
     * @return
     */

    @Override
    public ResponseBo updateAppOneUser(MyUser user) {
        try {
            if(StringUtils.isNotBlank(user.getMobile())){
                MyUser users= new MyUser();
                users.setMobile(user.getMobile());
                MyUser user1 = userMapper.selectOne(users);
                if(user1 != null){
                    if(!user.getUserId().equals(user1.getUserId())){
                        return ResponseBo.error("手机号被占用");
                    }
                }
                int row = userMapper.updateByPrimaryKeySelective(user);
                if(row == 1){
                    return ResponseBo.ok("更新成功");
                }
                return ResponseBo.error("更新失败");
            }
            int row = userMapper.updateByPrimaryKeySelective(user);
            if(row == 1){
                return ResponseBo.ok("更新成功");
            }
            return ResponseBo.error("更新失败");
        }catch (Exception e){
            e.printStackTrace();
            log.error("用户信息更新："+e.getMessage());
            return ResponseBo.error("系统错误");
        }
    }


    @Override
    public ResponseBo updateByPrimaryKey(MyUser user) {
        try {

            int row = userMapper.updateByPrimaryKeySelective(user);
            if(row == 1){
                return ResponseBo.ok("更新成功");
            }
            return ResponseBo.error("更新失败");
        }catch (Exception e){
            e.printStackTrace();
            log.error("用户信息更新："+e.getMessage());
            return ResponseBo.error("系统错误");
        }
    }
}
